package cn.xuqiudong.backend.config;

import cn.xuqiudong.backend.config.properties.RedirectConfigProperties;
import cn.xuqiudong.common.base.web.filter.SafelyRedirectFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 描述:
 *
 * @author Vic.xu
 * @since 2025-02-08 10:24
 */
@Configuration
@EnableConfigurationProperties(RedirectConfigProperties.class)
public class FilterConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(FilterConfig.class);


    private RedirectConfigProperties redirectConfigProperties;

    @Autowired
    public void setRedirectConfigProperties(RedirectConfigProperties redirectConfigProperties) {
        this.redirectConfigProperties = redirectConfigProperties;
    }

    /**
     * 避免重定向攻击
     */
    @Bean
    public FilterRegistrationBean<SafelyRedirectFilter> safelyRedirectFilter() {
        LOGGER.info("注册重定向过滤器:SafelyRedirectFilter");
        FilterRegistrationBean<SafelyRedirectFilter> registrationBean = new FilterRegistrationBean<>();
        SafelyRedirectFilter safelyRedirectFilter = new SafelyRedirectFilter();
        if (redirectConfigProperties.getWhiteList() != null) {
            LOGGER.info("白名单列表:\n\t{}" , String.join("\n\t" , redirectConfigProperties.getWhiteList()));
            safelyRedirectFilter.setWhiteList(redirectConfigProperties.getWhiteList());
        }
        registrationBean.setFilter(safelyRedirectFilter);
        // 适用于所有请求
        registrationBean.addUrlPatterns("/*");
        // 优先执行
        registrationBean.setOrder(1);
        return registrationBean;
    }
}
